import lombok.SneakyThrows;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 自定义类加载器。重写findClass 方法。
 *
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2021/4/21
 */
public class MyClassLoader extends ClassLoader {

    protected static final String filePath = "F:\\notion\\01JAVA\\file\\";

    @SneakyThrows
    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {

        // 将包里面 java.lang.String 命名规则修改为路径方式
        String desc = name.replaceAll("\\.","/");

        FileInputStream inputStream = new FileInputStream(filePath + desc + ".class");
        int length = inputStream.available();

        byte[] bytes = new byte[length];
        inputStream.read(bytes);

        return defineClass(name, bytes, 0, length);
    }
}
